<template>
    <jb-page>
        <template #conditions>
            <jb-icon icon="ant-design:sound-outlined"></jb-icon>
            <span>{{ $route.query.id ? '修改通知' : '发布新通知' }}</span>
        </template>
        <template #opt>
            <jb-btn type="primary" ghost icon="dashicons:yes" @click="submit">{{
                    $route.query.id ? '确认修改' : '确认发布'
                }}</jb-btn>
        </template>
        <template #default>
            <n-form
                ref="formRef"
                label-placement="left"
                :label-width="100"
                :model="form"
                :rules="rules"
            >
                <span class="text-16px"
                ><jb-icon
                    icon="clarity:form-line"
                    class="inline va--3 mr-4px"
                ></jb-icon
                >基本信息</span
                >
                <n-divider />
                <n-form-item label="标题" path="title">
                    <n-input v-model:value="form.title" placeholder="请输入标题" />
                </n-form-item>
                <n-form-item label="通知类型" path="type">
                    <jb-radio-group
                        v-model:value="form.type"
                        :value-to-number="true"
                        url="/api/admin/dictionary/options?typeKey=sys_notice_type"
                    ></jb-radio-group>
                </n-form-item>

                <n-form-item label="优先级" path="priorityLevel">
                    <jb-radio-group
                        v-model:value="form.priorityLevel"
                        :value-to-number="true"
                        url="/api/admin/dictionary/options?typeKey=sys_notice_priority_level"
                    ></jb-radio-group>
                </n-form-item>

                <n-form-item label="内容" path="content">
                    <jb-editor v-model="form.content" class="h-400px"></jb-editor>
                </n-form-item>
                <span class="text-16px"
                ><jb-icon
                    icon="teenyicons:attachment-outline"
                    class="inline va--3 mr-4px"
                ></jb-icon
                >附件上传</span
                >
                <n-divider />
                <n-form-item label="  ">
                    <jb-upload
                        v-model="form.files"
                        :multiple="true"
                        save-path="sysnotice/{date(yyMMdd)}/{random(6)}/{ori}"
                    >
                        <n-button>上传文件</n-button>
                    </jb-upload>
                </n-form-item>
                <span class="text-16px"
                ><jb-icon icon="fa6-solid:users" class="inline va--3 mr-4px"></jb-icon
                >接收者信息</span
                >
                <n-divider />
                <n-form-item :span="24" label="接收人" path="receiverType">
                    <jb-radio-group
                        v-model:value="form.receiverType"
                        :value-to-number="true"
                        url="/api/admin/dictionary/options?typeKey=sys_notice_receiver_type"
                        @change="changeReceiverType"
                    ></jb-radio-group>
                </n-form-item>
                <n-form-item :span="24" label="" path="receiverValue" class="pl-30px">
                    <jb-tree-select
                        v-if="form.receiverType == '2'"
                        v-model:value="form.receiverValue"
                        placeholder="请选择角色"
                        checkable
                        cascade
                        check-strategy="child"
                        url="/api/admin/role/datas"
                        multiple
                    ></jb-tree-select>
                    <jb-tree-select
                        v-if="form.receiverType == '3'"
                        v-model:value="form.receiverValue"
                        multiple
                        checkable
                        cascade
                        placeholder="请选择部门"
                        url="/api/admin/dept/enableOptions"
                    ></jb-tree-select>
                    <jb-select
                        v-if="form.receiverType == '4'"
                        v-model:value="form.receiverValue"
                        placeholder="请选择岗位"
                        url="/api/admin/post/options"
                        multiple
                    ></jb-select>
                    <n-input
                        v-if="form.receiverType == '5'"
                        :value="userNames"
                        readonly
                        placeholder="请选择用户"
                        multiple
                        @click="showModal = true"
                    ></n-input>
                </n-form-item>
            </n-form>
        </template>
    </jb-page>
    <n-modal v-model:show="showModal" class="max-w-1300px min-w-1300px">
        <template #default>
            <jb-crud-page
                ref="pageRef"
                title-text="请选择用户"
                title-icon="ic:round-manage-accounts"
                :search-conditions="searchForm"
                search-url="/api/admin/user/datas"
                @after-render="reChoose"
            >
                <template #conditions-form>
                    <n-input
                        v-model:value="searchForm.keywords"
                        type="text"
                        style="width: 130px"
                        placeholder="输入关键字搜索"
                    />

                    <jb-select
                        v-model:value="searchForm.sex"
                        url="/api/admin/dictionary/options?typeKey=sex"
                        placeholder="=性别="
                        class="w-100px"
                        filterable
                    ></jb-select>

                    <jb-select
                        v-model:value="searchForm.ofModule"
                        url="/api/admin/modules"
                        placeholder="=选择模块="
                        class="w-140px"
                        filterable
                    ></jb-select>
                    <jb-select
                        v-model:value="searchForm.enable"
                        url="/api/admin/dictionary/options?typeKey=options_enable"
                        placeholder="=状态="
                        class="w-100px"
                        filterable
                    ></jb-select>
                    <jb-tree-select
                        v-model:value="searchForm.roleId"
                        class="w-160px"
                        url="/api/admin/role/datas"
                        check-strategy="child"
                        placeholder="=角色="
                    ></jb-tree-select>
                </template>
                <template #default="{ state }">
                    <splitpanes class="default-theme">
                        <pane size="70">
                            <vxe-table
                                ref="tableRef"
                                border
                                :column-config="{ resizable: true }"
                                height="800"
                                show-header-overflow
                                show-overflow="tooltip"
                                :row-config="{
                                    height: 100,
                                    isHover: true,
                                    keyField: 'id'
                                }"
                                :seq-config="{ startIndex: state.tableStartIndex }"
                                align="center"
                                :data="state.list"
                                :checkbox-config="{
                                    checkRowKeys: userIdList,
                                    trigger: 'row'
                                }"
                                @checkbox-change="handleUserSelect"
                                @checkbox-all="handleUserSelectAll"
                            >
                                <jb-column type="checkbox" width="60"></jb-column>
                                <jb-column type="seq" title="序号" width="60"></jb-column>
                                <jb-column
                                    field="name"
                                    title="姓名"
                                    min-width="100"
                                ></jb-column>
                                <jb-column field="avatar" title="头像" width="100">
                                    <template #default="{ row }">
                                        <n-avatar
                                            v-if="row.avatar"
                                            round
                                            size="large"
                                            :src="row.avatar"
                                        >
                                        </n-avatar>
                                        <n-avatar v-else round size="large">
                                            <n-icon>
                                                <jb-icon
                                                    icon="carbon:user-avatar-filled"
                                                ></jb-icon>
                                            </n-icon>
                                        </n-avatar>
                                    </template>
                                </jb-column>
                                <jb-column field="sex" title="性别" width="60">
                                    <template #default="{ row }">
                                        <n-tag
                                            v-if="row.sex"
                                            :type="row.sex === 1 ? 'success' : 'warning'"
                                        >{{
                                                row?.sex === 1
                                                    ? '男'
                                                    : row?.sex === 2
                                                        ? '女'
                                                        : ''
                                            }}</n-tag
                                        >
                                    </template>
                                </jb-column>
                                <jb-column field="role" title="角色" min-width="120">
                                    <template #default="{ row }">
                                        <n-scrollbar
                                            v-if="row.userRoles?.length > 0"
                                            style="max-height: 100px"
                                        >
                                            <jb-tag-group
                                                :vertical="true"
                                                :tags="
                                                    row.userRoles?.map((i: any) => i.name)
                                                "
                                            ></jb-tag-group>
                                        </n-scrollbar>
                                        <span v-else>未设置</span>
                                    </template>
                                </jb-column>
                                <jb-column
                                    field="username"
                                    title="用户名"
                                    min-width="300"
                                ></jb-column>
                            </vxe-table>
                        </pane>
                        <pane size="30" style="background-color: #fff">
                            <n-tag
                                v-for="(item, index) in userNameList"
                                class="mr-5 mb-2"
                                type="primary"
                                closable
                                @close="handleUserRemove(item, index)"
                            >{{ item }}</n-tag
                            >
                        </pane>
                    </splitpanes>
                </template>
            </jb-crud-page>
        </template>
    </n-modal>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import type { FormInst, FormItemRule, FormRules } from 'naive-ui'
import { VxeTableDefines } from 'vxe-table'
import { useTabStore } from '@/store'
import { Rules } from '@/utils'
import { JBoltApi } from '@/utils/request'
import { useResetableData } from '@/hooks/common/use-resetable-data'
import { ResData } from '@/typings/request'
import JbCrudPage from '@/components/_builtin/jb-crud-page/index.vue'
import JbTagGroup from '@/components/_builtin/jb-tag-group/index.vue'
import { Model } from '@/typings/api'
import type { VxeTableInstance } from 'vxe-table'

const route = useRoute()
const pageRef = ref<InstanceType<typeof JbCrudPage> | null>(null)

/** 表单相关 start */
const formRef = ref<FormInst | null>()
interface InformType {
    id: string
    title: string
    type: number
    files: string
    content: string
    priorityLevel: number
    receiverType: number | string
    receiverValue: string[]
}
const form = useResetableData<InformType>({
    id: '',
    title: '',
    type: 1,
    content: '<p></p>',
    files: '',
    priorityLevel: 1,
    receiverType: 1,
    receiverValue: []
})
const rules: FormRules = reactive({
    title: new Rules().required('请输入标题').value,
    type: new Rules().required('请选择通知类型').value,
    content: new Rules().required('请输入内容').push({
        validator(rule: FormItemRule, value: string) {
            if (!value || contentIsEmpty(value)) {
                return new Error('请输入内容')
            }
            return true
        },
        trigger: ['blur']
    }).value,
    priorityLevel: new Rules().required('请选择优先级').value,
    receiverType: new Rules().required('请选择接收者类型').value,
    receiverValue: new Rules().value
})
function changeReceiverType() {
    form.receiverValue = []
    userIdList.value = []
    userNameList.value = []
    const newRules = new Rules().required('请输入接收者信息')
    if (form.receiverType == '1') {
        newRules.delete(0)
    }

    rules.receiverValue = newRules.value
}

/**
 * 提交表单
 */
async function submit() {
    await formRef.value?.validate()
    let url = route.query.id ? '/api/admin/sysNotice/update' : '/api/admin/sysNotice/save'
    const data: any = { ...form }
    data.receiverValue = data.receiverValue.join(',')
    await JBoltApi.tryPost(url, data)
    await useTabStore().closeCurrentTab()
    // await router.replace({ name: PageNames.SYSNOTICE_MGR, query: { reset: 'true' } })
    return true
}

// 使用正则表达式匹配字符串中是否包含 <img> 或者 <video> 标签
function contentIsEmpty(str: string) {
    const imgRegex = /<img\b[^>]*>/i
    const videoRegex = /<video\b[^>]*>/i
    const hasImgTag = imgRegex.test(str)
    const hasVideoTag = videoRegex.test(str)
    // 返回判断结果
    if (hasImgTag || hasVideoTag) {
        return false
    } else {
        const regex = /(<([^>]+)>)/gi
        const result = str.replace(regex, '')
        return !result
    }
}
function loadEditData() {
    JBoltApi.get<ResData>(`/api/admin/sysNotice/${route.query.id}`).then(
        ({ error, result }) => {
            if (error) return
            result.data.receiverValue = result.data.receiverValue.split(',')
            if (result.data.receiverType == '5') {
                userIdList.value = result.data.receiverValue
                userNameList.value = result.data.receiverValues.split(',')
            }
            form._reset(result.data)
        }
    )
}

onMounted(() => {
    if (route.query.id) {
        loadEditData()
    }
})

defineExpose({
    submit
})

/** 表单相关 end */

const showModal = ref(false)
const tableRef = ref<VxeTableInstance<any>>()
const userIdList = ref<any>([])
const userNameList = ref<any>([])
const userNames = computed(() => {
    return userNameList.value.join(',')
})
watch(
    () => userIdList.value,
    (newVal) => {
        form.receiverValue = userIdList.value
        console.debug('111', form.receiverValue)
    },
    {
        deep: true
    }
)

const searchForm = useResetableData({
    keywords: '',
    ofModule: '',
    sex: '',
    roleId: '',
    enable: '',
    postId: '',
    deptId: ''
})

function reChoose(list: Model[]) {
    const $table = tableRef.value
    if ($table) {
        $table.setCheckboxRow(
            userIdList.value.map((id) => list.find((item) => item.id == id)),
            true
        )
    }
}

function handleUserSelectAll({
                                 checked
                             }: VxeTableDefines.CheckboxChangeEventParams<any>) {
    let list = pageRef?.value?.state?.list
    list?.forEach((item) => {
        let index = userIdList.value.findIndex((i: any) => i == item.id)
        if (checked && index == -1) {
            userIdList.value.push(item.id)
            userNameList.value.push(item.name)
        } else if (!checked && index >= 0) {
            userIdList.value.splice(index, 1)
            userNameList.value.splice(index, 1)
        }
    })
}
function handleUserSelect({
                              checked,
                              row
                          }: VxeTableDefines.CheckboxChangeEventParams<any>) {
    let index = userIdList.value.findIndex((i: any) => i == row.id)
    if (checked && index == -1) {
        userIdList.value.push(row.id)
        userNameList.value.push(row.name)
    } else if (!checked && index >= 0) {
        userIdList.value.splice(index, 1)
        userNameList.value.splice(index, 1)
    }
}

function handleUserRemove(item: any, index: number) {
    const $table = tableRef.value
    let findIndex = $table?.getCheckboxRecords().findIndex((i) => i.name == item)!
    if (findIndex >= 0) {
        $table?.setCheckboxRow($table.getCheckboxRecords()[findIndex], false)
    }
    userIdList.value.splice(index, 1)
    userNameList.value.splice(index, 1)
}
</script>
<style scoped></style>
